<template>
  <div id="login">
    <header>
      <img :src="loginInfo.logoPath" alt="百世伽科技" />
    </header>

    <main class="login-container"
          :style="{
      backgroundImage: 'url(' + backPath + ')',
      backgroundPosition:'center center',
      backgroundRepeat:'no-repeat'}">
      <section class="login-title">
        <p>{{ loginInfo.title }}</p>
        <p>{{ loginInfo.slogan }}</p>
      </section>

      <section class="login-account">
        <div class="login-account-wrap">

          <h2 class="w" @click="showCode">用户登录 / User login</h2>

          <div class="horizontal-line"></div>

          <el-form class="w" :model="loginForm" :rules="rules" ref="loginForm">

            <!-- 错误提示 -->
            <el-form-item class="err-wrap" label="" v-show="loginErrorInfo">
              <div class="err-content">
                <i class="iconfont iconminus-circle-fill"></i>
                <span>{{ loginErrorInfo }}</span>
              </div>
            </el-form-item>

            <!-- 账号 -->
            <el-form-item label="" prop="account">
              <el-input v-dcp v-model.trim="loginForm.account" placeholder="请输入姓名" maxlength="15" @blur="showCode">
                <i slot="prefix" class="iconfont iconuser"></i>
              </el-input>
            </el-form-item>

            <!-- 密码 -->
            <el-form-item label="" prop="password">
              <el-input v-dcp type="password" v-model.trim="loginForm.password" placeholder="请输入密码" maxlength="15">
                <i slot="prefix" class="iconfont iconlock1"></i>
              </el-input>
            </el-form-item>

            <el-form-item
                v-if="codeVisible"
                class="code-wrap animated flipInX"
                :class="{'is-error': this.loginErrorInfo === '请输入验证码'}"
                label="">
              <el-input v-dcp v-model.trim="loginForm.code" placeholder="请输入验证码" maxlength="4"
                        @input="val=>changeCodeValue(val)">
              </el-input>
              <img class="code-img" :src="codePath" alt="" @click="getCode">
            </el-form-item>


            <el-form-item label="">
              <input type="submit"
                     class="login_block_button ant-btn ant-btn-primary ant-btn-block"
                     @click="login('loginForm')"
                     :loading="loginLoad"
                     :disabled="disabledLogin" value="登录">
            </el-form-item>
          </el-form>

          <div class="w password-handle">
            <el-checkbox v-model="rememberThePassword">记住密码</el-checkbox>
          </div>

        </div>
      </section>
    </main>

    <footer v-html="CDATA.LOGIN_FOOTER_MSG">

    </footer>
  </div>
</template>

<script>
import {mapActions, mapMutations} from 'vuex';
import CryptoJS from '@/utils/aes';
import base from '@/api/modules/auth/base';

export default {
  name: 'Login',

  watch: {
    loginInfo: {
      deep: true,
      handler: function (newVal, oldVal) {
        if (Object.values(newVal).filter(item => true).length === 4) {
          this.tools.saveS('loginInfo', newVal);
        }
      }
    }
  },

  data() {
    let validateName = (rule, value, callback) => {
      if (this.loginErrorInfo === '账号已锁定10分钟') {
        return callback();
      }
      if (!value) {
        this.loginErrorInfo = '请输入用户名';
        return callback(new Error(' '));
      } else {
        this.loginErrorInfo = '';
        return callback();
      }
    };

    // 密码验证
    let validatePsw = (rule, value, callback) => {
      if (this.loginErrorInfo === '账号已锁定10分钟') {
        return callback();
      }
      if (!value) {
        this.loginErrorInfo = '请输入密码';
        return callback(new Error(' '));
      } else {
        this.loginErrorInfo = '';
        return callback();
      }
    };

    return {

      projectKey: 'arp',

      loginForm: {
        account: '',
        password: '',
        code: '',
      },
      rules: {
        account: [{validator: validateName, trigger: 'change'}],
        password: [{validator: validatePsw, trigger: 'change'}],
      },

      // 显示验证码
      codeVisible: false,

      // 按钮加载
      loginLoad: false,

      // 是否禁止登录
      disabledLogin: false,

      // 记住密码是否勾选
      rememberThePassword: this.tools.getS('isRememberCheck'),

      // 登录错误信息
      loginErrorInfo: '',

      // 验证码地址
      codePath: '',

      // 验证码内容
      codeContent: '',

      loginInfo: {
        // logo图片
        logoPath: '',

        // 项目文字
        title: '',
        slogan: '',

        // 底部文字
        footerText: '',
      },

      // 背景图片
      backPath: window.backPath || (require('@/assets/img/login/login_back.png'))

    };
  },

  created() {
    this.getLoginInfo(101);
  },

  mounted() {
    this.fitAccount();
    window.addEventListener('keydown', this.keyDown);
  },

  beforeDestroy() {
    window.removeEventListener('keydown', this.keyDown, false);
  },

  methods: {
    ...mapMutations(['setUser']),
    ...mapActions(['setUserA']),

    // 获取登录信息
    async getLoginInfo(type) {
      // 先查看本地是否有存储的信息
      let loginInfo = this.tools.getS('loginInfo');

      if (loginInfo) {
        this.loginInfo = loginInfo;
        return;
      }

      const res = await this.$api.auth.getLoginInfo({
        parentSystemCode: type
      });

      console.log(res);

      if (res.data.type === 'success') {
        this.loginInfoHandle(res.data.data, type);
      }

    },

    loginInfoHandle(res, type) {
      res.forEach(item => {
        if (item.systemCode === '101101') {
          this.loginInfo.title = this.tools.htmlDecode(item.systemValue);
        }
        if (item.systemCode === '101102') {
          this.loginInfo.slogan = this.tools.htmlDecode(item.systemValue);
        }
        if (item.systemCode === '101103') {
          this.loginInfo.footerText = this.tools.htmlDecode(item.systemValue);
        }
        if (item.systemCode === '101100') {
          this.loginInfo.logoPath = this.tools.htmlDecode(base.prod + item.systemValue);
        }
      });
    },

    // 加密
    aesMinEncrypt(data, key, iv) {
      let _word = CryptoJS.enc.Utf8.parse(data),
        _key = CryptoJS.enc.Utf8.parse(key),
        _iv = CryptoJS.enc.Utf8.parse(iv);
      let encrypted = CryptoJS.AES.encrypt(_word, _key, {
        iv: _iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });
      return encrypted.toString();
    },

    encryption(password) {
      //密钥 (需要前端和后端保持一致)十六位作为密钥
      let key = 'ABCDEFGHIJKL_key';
      //密钥偏移量 (需要前端和后端保持一致)十六位作为密钥偏移量
      let iv = 'ABCDEFGHIJKLM_iv';
      return this.aesMinEncrypt(password, key, iv);
    },

    encode(value) {
      return this.tools.base64Handle().encode(value);
    },

    decode(value) {
      return this.tools.base64Handle().decode(value);
    },

    // 自动填充账号
    fitAccount() {
      if (this.rememberThePassword) {
        let account = JSON.parse(this.tools.getCookie(this.projectKey));
        console.log(account);

        if (this.tools.getType(account) === 'Object' && account.hasOwnProperty('k') && account.k === this.projectKey) {
          this.loginForm.account = this.decode(account.a.n);
          this.loginForm.password = this.decode(account.a.p);
        }
      }
    },

    login(formName) {
      event.preventDefault();
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.codeVisible && !this.checkCode()) {
            return;
          }
          // 按钮加载
          this.loginLoad = true;
          try {
            let param = {
              account: this.loginForm.account,
              password: this.encryption(this.loginForm.password),
            };

            // 发送请求向后台验证用户名以及密码的正确与否
            const res = await this.$api.auth.getLogin({
              ...param
            });
            // console.log(res);
            if (res.data.type === 'success') {
              let {data: user} = res.data;
              // console.log(user);
              let userData = {
                // 账号
                admin: user.account,
                // 用户名
                userName: user.userName,
                // token
                token: user.token
              };
              this.setUser(userData);
              this.tools.saveS('user', user.account, 2);
              this.tools.saveS('userName', user.userName, 2);
              this.tools.saveS('token', '', 2);
              // 是否记住密码

              this.rememberHandle();

              this.tools.saveS('isRememberCheck', this.rememberThePassword);

              this.loginLoad = false;

              // 检查参数是否有需要去跳转的页面，否则跳转首页
              let redirect = this.$route.query.redirect || '/';

              await this.$router.replace(redirect);

            } else {
              this.loginErrHandle(res.data.code, res.data.msg);
              this.loginLoad = false;
            }
          } catch (e) {
            console.warn(e + '');
            this.loginLoad = false;
          }

        } else {
          return false;
        }
      });
    },

    // 返回信息错误处理
    loginErrHandle(code, msg) {
      (code === '001') && (this.loginErrorInfo = msg);
      (code === '011') && (this.showCodeHandle(1));
    },

    changeCodeValue(val) {
      this.loginErrorInfo = (val === '') ? '请输入验证码' : '';
    },
    // 验证码验证
    checkCode() {
      if (this.loginForm.code === '' && this.loginErrorInfo === '') {
        this.loginErrorInfo = '请输入验证码';
        console.log(this.loginErrorInfo);
        return false;
      }

      if (this.loginForm.code && (this.loginForm.code).toLowerCase() !== this.codeContent) {
        this.loginErrorInfo = '验证码输入错误';
        this.loginForm.code = '';
        return false;
      }

      return true;
    },

    // 是否需要显示验证码
    async showCode() {
      if (!this.loginForm.account) {
        return;
      }

      let param = {
        account: this.loginForm.account
      };

      const res = await this.$api.auth.getNeedCode({
        ...param
      });

      if (res.data.type === 'success') {
        this.showCodeHandle(res.data.data);
      }
    },

    showCodeHandle(type) {
      /*
      *
      *  0 页面不显示验证码
      *  1 页面显账号锁定
      *  2 页面显示验证码
      *
      * */
      switch (type) {
        case 0:
          this.loginErrorInfo = '';
          this.codeVisible = false;
          this.disabledLogin = false;
          break;
        case 1:
          // debugger
          this.loginErrorInfo = '账号已锁定10分钟';
          this.disabledLogin = true;
          break;
        case 2:
          this.loginErrorInfo = '';
          this.disabledLogin = false;
          this.getCode();
          this.codeVisible = true;
          break;
      }
    },

    // 获取验证码
    getCode() {
      this.$api.auth.getCode((data) => {
        // console.log(data);
        this.getCodeContent();
        this.codePath = data;
      });
    },

    // 获取验证码的内容
    async getCodeContent() {
      const res = await this.$api.auth.getCodeContent();
      console.log('验证码内容：', res.data.data);
      this.codeContent = (res.data.data).toLowerCase();
    },

    // 记住密码
    rememberHandle() {
      if (this.rememberThePassword) {
        // 选择了是 存储一个对象，里面带了加密的用户名和密码，和当前系统的标识
        let rp = {
          k: this.projectKey,
          a: {
            n: this.encode(this.loginForm.account),
            p: this.encode(this.loginForm.password)
          }
        };

        this.tools.saveCookie(this.projectKey, JSON.stringify(rp), 7);

      } else {
        // 选择了否 直接删除cookie，无需判断想删除的项是否存在
        this.tools.delCookie([this.projectKey]);
      }
    },

    keyDown(e) {
      // console.log(e)
      //如果是回车则执行登录方法
      if (e.keyCode === 13) {
        this.login('loginForm');
      }
    },

  },
};
</script>

<style scoped lang="less">
  @import url("~@/assets/css/login/login.less");
</style>
